package gotnames.web.st;

import gotnames.Utils;
import gotnames.dm.User;

import java.util.Collection;
import java.util.Comparator;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.medallia.tiny.CollUtils;

/**
 * Task which displays a table ranking all users in the group.
 */
public class LeaderBoardTask extends GotNamesTask {
	
	@Output interface Values {
		V<Collection<User>> USERS = v();
	}
	
	void action(User user, PersistenceManager pm) {
		
		Query q = pm.newQuery(User.class);
		q.setFilter("groupKey == " + user.getGroupKey());
		q.setOrdering("firstName ASC, lastName ASC");
		Collection<User> users = Utils.<Collection<User>>cast(q.execute());
		
		attr(Values.USERS, CollUtils.sortedCopy(users, new Comparator<User>() {
			@Override public int compare(User u1, User u2) {
				Double d1 = u1.getPstCorrectGuessesDouble();
				Double d2 = u2.getPstCorrectGuessesDouble();
				
				boolean nan1 = d1.isNaN();
				boolean nan2 = d2.isNaN();
				
				// NaNs should go last
				if (nan1) {
					return nan2 ? 0 : 1;
				} else if (nan2) {
					return -1;
				} else {
					int v = d2.compareTo(d1);
					// Use num correct guesses to break ties
					return v != 0 ? v : u2.getNumCorrectGuesses() - u1.getNumCorrectGuesses();
				}
			}
		}));
	}

	@Override public String getPageTitle() { return "Leader Board"; }

}
